package cn.zysoft.his4killsession.service.impl;

import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.zysoft.his4killsession.dao.BlockInfoDao;
import cn.zysoft.his4killsession.factory.DataSourceContextHolder;
import cn.zysoft.his4killsession.pojo.BlockInfo;
import cn.zysoft.his4killsession.service.BlockInfoService;
import cn.zysoft.his4killsession.util.LoadPropertiesUtil;
@Service
public class BlockInfoServiceImpl implements BlockInfoService {
	@Autowired
	private BlockInfoDao blockInfoDao;
	
	private Exception exception;
	
	private void cleanSession(String dataSource,String sessionInfo){
		DataSourceContextHolder.setDataSourceType(dataSource);
		String[] splitSession = sessionInfo.split("n");
		String sessionNum = splitSession[1];
		sessionNum = sessionNum.split("阻")[0].trim();
		blockInfoDao.killSession(sessionNum);
	}
	
	public List<BlockInfo> selectBlockInfo() {
		String defaultdatabase = LoadPropertiesUtil.readProp("defaultdatasource.properties","database");
		if(defaultdatabase.equals("1")){
			DataSourceContextHolder.setDataSourceType("LOADBALANCE");
		}
		List<BlockInfo> blockInfos = blockInfoDao.selectBlockInfo();
		//>0说明出现阻塞
		try{
		if(blockInfos.size()>0){
			for (BlockInfo blockInfo : blockInfos) {
				String instId = blockInfo.getInstId().trim();
				//如果sid为1设置数据源为ONESERVER
				if(instId.equals("1")){
					cleanSession("ONESERVER", blockInfo.getBlockInfo());
				}else{
					cleanSession("TWOSERVER", blockInfo.getBlockInfo());
				}
			}
		}
		}catch(Exception ex){
			exception = ex;
			ex.printStackTrace();
		}finally{
			//如果会话被自动清楚，自调用方法继续查锁  ORA-00026: 丢失或无效的会话 ID
			if(exception instanceof SQLException && exception.getMessage().equals("ORA-00026")){
			selectBlockInfo();
			}
		}
		return blockInfos;
	}

}
